package as3.carcassone.view {
	import as3.carcassone.model.Model;
	import as3.carcassone.model.PopupManager;
	import as3.carcassone.tiles.IGameTile;

	import nl.ypmits.font.FontsHelveticaNeue;
	import nl.ypmits.font.TextFieldUtility;
	import nl.ypmits.form.Button;

	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.text.TextFieldAutoSize;

	public class TilePicker extends Sprite {
		private var _numTilesLeft : TextFieldUtility;
		
		public function TilePicker()
		{
			draw();
			
			Model.instance.addEventListener( Event.CHANGE, changeHandler );
		}



		private function changeHandler( e : Event ) : void
		{
			trace("TilePicker.changeHandler("+[e]+")");
			_numTilesLeft.text = "Cards left: " + String( Model.instance.tiles.length );
		}



		private function draw() : void
		{
			_numTilesLeft = new TextFieldUtility( "", FontsHelveticaNeue.HELVETICA_BOLD, 18, 0xFFFFFF );
			_numTilesLeft.textfield.autoSize = TextFieldAutoSize.LEFT;
			_numTilesLeft.textfield.selectable = false;
			_numTilesLeft.text = "Cards left: " + String( Model.instance.tiles.length );
			addChild( _numTilesLeft );

			with( graphics ) {
				beginFill( 0xFF0000 );
				drawRect( 0, 0, 300, 350 );
				endFill();
			}
			addChild( new Button( "Next turn", FontsHelveticaNeue.HELVETICA_BOLD, 10, 300, 130, 42, pickRandomTile ) );
		}



		public function pickRandomTile( e : MouseEvent ) : void
		{
			var tile : IGameTile = Model.instance.pickRandomTile();
			if ( tile )
			{
				tile.x = width * .5;
				tile.y = height * .5 - 10;
				tile.unlock();
				addChild( tile.view.graphic );
			} else {
				// Do the 'NO-MORE-CARDS-LEFT' action
				PopupManager.instance.showWarning( "No more cards left!" );
			}
		}
	}
}
